#include"Server.h"
#include<QWidget>
#include<QMessageBox>
#include<QHostInfo>
#include <QSqlDriver>

Server::Server(QObject *parent, int port)
        :QTcpServer(parent){
    listen(QHostAddress::Any,port);
    if(!isListening()){
        QWidget tmp;
        QMessageBox::information(&tmp,tr("Error"),tr("Listening to port 8888 failed!"));
        exit(EXIT_FAILURE);
    }

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");  //使用QSQLite数据库驱动
    qDebug()<< QHostInfo::localHostName();
    db.setHostName(QHostInfo::localHostName());              //设置数据库主机名
    db.setDatabaseName("History");                           //设置数据库名
    if(!db.open()){                                          //打开连接
         qDebug()<< "open failed!" << endl;
         exit(1);
    }
    QSqlQuery query;
    bool ok = query.exec("create table Record(msg varchar)");  //创建一张表
    qDebug()<< ok;

}

Server::~Server(){
}

void Server::updateClient(QString str){
    emit updateServerUI(str);
    QString tmp = "insert into Record values (\'" + str + "\')";
    qDebug()<<tmp;
    QSqlQuery query;
    query.exec(tmp);

    str.insert(0,'1');
    QByteArray data = str.toLatin1();
    for(int i = 0; i < ClientList.count(); ++i){
        Client *client = ClientList.at(i);
        client->write(data);
    }
}

void Server::slotdisconnect(int descripter){
    for(int i = 0; i < ClientList.count(); ++i){
        Client *client = ClientList.at(i);
        if(client->socketDescriptor() == descripter){
            ClientList.removeAt(i);
            return;
        }
    }
}

void Server::slotClose(){
    for(QList<Client *>::const_iterator it = ClientList.cbegin(); it < ClientList.cend(); ++it)
           (*it)->disconnectFromHost();
    ClientList.clear();
    QSqlQuery query;
    query.exec("delete * from Record");
    emit updateServerUI("done! left " + QString::number(ClientList.count()));
    this->~Server();
}


void Server::incomingConnection(qintptr descripter){
     Client *client = new Client(this);
     client->setSocketDescriptor(descripter);

     connect(client,SIGNAL(updateServer(QString)),this,SLOT(updateClient(QString)));
     connect(client,SIGNAL(disconnect(int)),this,SLOT(slotdisconnect(int)));

     QSqlQuery query("select * from Record");
     while(query.next()){
         QString str(query.value("msg").toString());
         str.insert(0,'0');
         QByteArray array = str.toLatin1();
         client->write(array);
     }

     ClientList.append(client);
}
